package com.teng.smartdrawer;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.teng.smartdrawer.bean.Recommend;
import com.teng.smartdrawer.bean.Seek;
import com.teng.smartdrawer.fragments.SearchRecordFragment;
import com.teng.smartdrawer.fragments.SearchResultFragment;
import com.teng.smartdrawer.listener.SearchKeywordListener;
import com.teng.smartdrawer.listener.TextIsNull;
import com.teng.smartdrawer.parser.DataConstants;
import com.teng.smartdrawer.parser.DataParser;
import com.teng.smartdrawer.utils.CustomDialog;
import com.teng.smartdrawer.utils.Utils;
import com.teng.smartdrawer.view.ClearEditText;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;


public class SearchActivity extends FragmentActivity implements TextIsNull, TextView.OnEditorActionListener {

    SearchRecordFragment recordFragment;
    SearchResultFragment resultFragment;
    ClearEditText edit_search;
    private FragmentTransaction transaction;
    private String content;
    private DbManager db = x.getDb(Utils.daoConfig);

    private List<Seek> seekList;

    private Dialog progressDialog;

//    Collection

//    HashSet

//    Map

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        initView();

        transaction = getSupportFragmentManager().beginTransaction();
        recordFragment = new SearchRecordFragment();
        resultFragment = new SearchResultFragment();

        progressDialog = CustomDialog.createLoadingDialog(this, "正在搜索...");

        recordFragment.setSearchKeywordListener(new SearchKeywordListener() {
            @Override
            public void search(String tempContent) {
                content = tempContent;
                if (content != null && !"".equals(content)){

                    getSupportFragmentManager().beginTransaction().show(resultFragment).hide(recordFragment).commit();
                    seekList = query();

                    for (int i = 0; i < seekList.size(); i++) {
                        if (seekList.get(i).getName().equals(content)){
                            try {
                                db.delete(seekList.get(i));
                            } catch (DbException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    progressDialog.show();
                    DataParser.getSearchContent(SearchActivity.this, handler, content);
                }else {
                    Toast.makeText(SearchActivity.this, "搜索内容不能为空", Toast.LENGTH_SHORT).show();
                }
            }
        });

        transaction.add(R.id.search_food_frame_container, recordFragment)
                .add(R.id.search_food_frame_container, resultFragment)
                .show(recordFragment)
                .hide(resultFragment)
                .commit();

    }

    /**
     * 查找搜有的搜索记录
     */
    private List<Seek> query() {
        List<Seek> ret = null;
        try {
            ret = db.findAll(Seek.class);

            if (ret.size() > 8){
                ret = ret.subList(0 , 7);
            }

            if (ret == null) {
                ret = new ArrayList<Seek>();
            }

        } catch (DbException e) {
            e.printStackTrace();
        }
        return ret;
    }

    private void initView() {
        edit_search = (ClearEditText) findViewById(R.id.edit_search);
        edit_search.setOnEditorActionListener(this);
        edit_search.setTextIsNull(this);    // 监听输入框是否为空
    }


    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            if (progressDialog != null && progressDialog.isShowing()){
                progressDialog.dismiss();
            }

            switch (msg.what){
                case DataConstants.GET_SEARCH_SIGN:

                    List<Recommend> data = (List<Recommend>) msg.obj;

                    if (data == null || data.size() == 0) {
                        getSupportFragmentManager().beginTransaction().show(recordFragment).hide(resultFragment).commit();
                        Toast.makeText(SearchActivity.this , "没有搜索结果" , Toast.LENGTH_SHORT).show();
                    }else {
                        getSupportFragmentManager().beginTransaction().show(resultFragment).hide(recordFragment).commit();
                        resultFragment.updateData(data);
                        insert();   //保存搜索记录到数据库
                    }

                    break;
                case DataConstants.ERROR:
                    getSupportFragmentManager().beginTransaction().show(recordFragment).hide(resultFragment).commit();
                    Toast.makeText(SearchActivity.this , "没有搜索结果" , Toast.LENGTH_SHORT).show();
                    break;
                default:

                    break;
            }

            return false;
        }
    });

    /**
     * 将搜索记录插入数据库
     */
    private void insert() {
        try {
            Seek seek = new Seek();
            seek.setName(content);
            seek.setSeekTime(System.currentTimeMillis());
            db.save(seek);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void textIsNull() {
        // TODO 搜索文本为空
        getSupportFragmentManager().beginTransaction().show(recordFragment).hide(resultFragment).commit();
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        // TODO 键盘发送搜索请求
        if ((actionId == 0 || actionId == 3) && event != null) {
            // TODO 搜索按钮
            content = edit_search.getText().toString();

            if (content != null && !"".equals(content)){

                getSupportFragmentManager().beginTransaction().hide(recordFragment).show(resultFragment).commit();

                seekList = query();

                for (int i = 0; i < seekList.size(); i++) {
                    if (seekList.get(i).getName().equals(content)){
                        try {
                            db.delete(seekList.get(i));
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }
                }

                progressDialog.show();
                DataParser.getSearchContent(this, handler, content);
            }else {
                Toast.makeText(this, "搜索内容不能为空", Toast.LENGTH_SHORT).show();
            }
        }
        return false;
    }

    public void btnBackClick(View view) {
        finish();
    }

    public void btnSearchFood(View view) {
        // TODO 搜索按钮
        content = edit_search.getText().toString();
        if (content != null && !"".equals(content)){

            getSupportFragmentManager().beginTransaction().show(resultFragment).hide(recordFragment).commit();
            seekList = query();

            for (int i = 0; i < seekList.size(); i++) {
                if (seekList.get(i).getName().equals(content)){
                    try {
                        db.delete(seekList.get(i));
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                }
            }
            progressDialog.show();
            DataParser.getSearchContent(this, handler, content);
        }else {
            Toast.makeText(this, "搜索内容不能为空", Toast.LENGTH_SHORT).show();
        }
    }

//    private void searchKeyword(String contentTemp) {
//
//        content = contentTemp;
//
//        if (content != null && !"".equals(content)){
//
//            getSupportFragmentManager().beginTransaction().show(resultFragment).hide(recordFragment).commit();
//            seekList = query();
//
//            for (int i = 0; i < seekList.size(); i++) {
//                if (seekList.get(i).getName().equals(content)){
//                    try {
//                        db.delete(seekList.get(i));
//                    } catch (DbException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//            progressDialog.show();
//            DataParser.getSearchContent(this, handler, content);
//        }else {
//            Toast.makeText(this, "搜索内容不能为空", Toast.LENGTH_SHORT).show();
//        }
//    }
}
